package com.ruoyi.training.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;
import com.ruoyi.training.domain.*;
import com.ruoyi.training.dto.MyExamInfo;
import com.ruoyi.training.dto.StudentsDto;
import com.ruoyi.training.mapper.*;
import com.ruoyi.training.service.ITrainingClassService;
import com.ruoyi.training.util.xuehua.SnowflakeIdUtils;
import com.ruoyi.training.vo.TrainClassVo;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.ruoyi.training.dto.registration.RegistrationDto;
import com.ruoyi.training.service.IRegistrationService;
import com.ruoyi.training.service.IStudentsService;
import com.ruoyi.training.vo.ClassStudentVO;
import com.ruoyi.training.vo.registration.RegistrationVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.training.service.IClassStudentService;

/**
 * 班级学员明细Service业务层处理
 *
 * @author WorrilessGo
 * @date 2025-09-24
 */
@Service
public class ClassStudentServiceImpl implements IClassStudentService {
    private static final Logger log = LoggerFactory.getLogger(ClassStudentServiceImpl.class);

    private static final SnowflakeIdUtils snowflake = new SnowflakeIdUtils(5, 8);

    @Autowired
    private ClassStudentMapper classStudentMapper;

    @Autowired
    private IRegistrationService registrationService;

    @Autowired
    private IStudentsService studentsService;

    @Autowired
    private TrainingClassMapper trainingClassMapper;

    @Autowired
    private ITrainingClassService trainingClassService;

    @Autowired
    private UnitsMapper unitsMapper;

    @Autowired
    private CertificateIssueMapper certificateIssueMapper;

    @Autowired
    private SpecialCertificateMapper specialCertificateMapper;

    @Autowired
    private ProjectsMapper projectsMapper;

    @Autowired
    private ExamScheduleMapper examScheduleMapper;

    /**
     * 查询班级学员明细
     *
     * @param classStudentId 班级学员明细主键
     * @return 班级学员明细
     */
    @Override
    public ClassStudent selectClassStudentByClassStudentId(String classStudentId) {
        return classStudentMapper.selectClassStudentByClassStudentId(classStudentId);
    }

    /**
     * 查询班级学员明细列表
     *
     * @param classStudent 班级学员明细
     * @return 班级学员明细
     */
    @Override
    public List<ClassStudent> selectClassStudentList(ClassStudent classStudent) {
        return classStudentMapper.selectClassStudentList(classStudent);
    }

    /**
     * 新增班级学员明细
     *
     * @param classStudent 班级学员明细
     * @return 结果
     */
    @Override
    public int insertClassStudent(ClassStudent classStudent) {
        classStudent.setCreateTime(DateUtils.getNowDate());
        return classStudentMapper.insertClassStudent(classStudent);
    }

    /**
     * 修改班级学员明细
     *
     * @param classStudent 班级学员明细
     * @return 结果
     */
    @Override
    public int updateClassStudent(ClassStudent classStudent) {
        classStudent.setUpdateTime(DateUtils.getNowDate());
        return classStudentMapper.updateClassStudent(classStudent);
    }

    /**
     * 批量删除班级学员明细
     *
     * @param classStudentIds 需要删除的班级学员明细主键
     * @return 结果
     */
    @Override
    public int deleteClassStudentByClassStudentIds(String[] classStudentIds) {
        return classStudentMapper.deleteClassStudentByClassStudentIds(classStudentIds);
    }

    /**
     * 删除班级学员明细信息
     *
     * @param classStudentId 班级学员明细主键
     * @return 结果
     */
    @Override
    public int deleteClassStudentByClassStudentId(String classStudentId) {
        return classStudentMapper.deleteClassStudentByClassStudentId(classStudentId);
    }

//    /**
//     * 根据班级ID查询所有相关的报名信息和学员信息
//     * lqx
//     * @param trainingClassId 班级ID
//     * @return 包含报名信息和学员信息的列表
//     */
//    @Override
//    public List<ClassStudentVO> getClassStudents(String trainingClassId) {
//        List<ClassStudentVO> resultList = new ArrayList<>();
//
//        try {
//            // 查询该班级所有在班学员
//            List<ClassStudent> classStudents = classStudentMapper.selectClassStudentsByClassId(trainingClassId);
//            if (classStudents == null || classStudents.isEmpty()) {
//                log.info("班级ID: {} 没有找到在班学员记录", trainingClassId);
//                return resultList;
//            }
//            System.out.println("classStudents = " + classStudents);
//
//            for (ClassStudent classStudent : classStudents) {
//                ClassStudentVO vo = new ClassStudentVO();
//
//                // 处理报名ID不为空的情况
//                if (classStudent.getRegistrationId() != null && !classStudent.getRegistrationId().trim().isEmpty()) {
//                    try {
//                        // 1. 构建查询条件VO
//                        RegistrationVo queryVo = new RegistrationVo();
//                        queryVo.setRegistrationId(classStudent.getRegistrationId());
//                        System.out.println("queryVo = " + queryVo.getRegistrationId());
//
//                        // 2. 调用修改后的selectList方法（参数为VO，返回DTO列表）
//                        List<RegistrationDto> registrationDtos = registrationService.selectList(queryVo);
//
//                        System.out.println("registrationDtos = " + registrationDtos);
//
//                        if (registrationDtos != null && !registrationDtos.isEmpty()) {
//                            vo.setSourceType("registration");
//                            vo.setRegistrationDto(registrationDtos.get(0));
//                            resultList.add(vo);
//                        } else {
//                            log.warn("报名ID: {} 未查询到对应报名信息", classStudent.getRegistrationId());
//                            // 若报名信息不存在，尝试查询学员信息
//                            addStudentInfoToResult(classStudent.getStudentId(), resultList);
//                        }
//                    } catch (Exception e) {
//                        log.error("查询报名ID: {} 信息出错", classStudent.getRegistrationId(), e);
//                        // 发生异常时，尝试查询学员信息作为备选
//                        addStudentInfoToResult(classStudent.getStudentId(), resultList);
//                    }
//                }
//                // 处理报名ID为空的情况
//                else {
//                    addStudentInfoToResult(classStudent.getStudentId(), resultList);
//                }
//            }
//        } catch (Exception e) {
//            log.error("查询班级学员信息出错", e);
//            // 这里可以根据实际情况决定是否抛出异常
//            // throw new ServiceException("查询班级学员信息失败", e);
//        }
//
//        return resultList;
//    }
//
//    /**
//     * 添加学员信息到结果列表
//     */
//    private void addStudentInfoToResult(String studentId, List<ClassStudentVO> resultList) {
//        if (studentId == null || studentId.trim().isEmpty()) {
//            log.warn("学员ID为空，无法查询学员信息");
//            return;
//        }
//
//        try {
//            Students student = studentsService.selectStudentsByStudentId(studentId);
//            if (student != null) {
//                ClassStudentVO vo = new ClassStudentVO();
//                vo.setSourceType("student");
//                vo.setStudent(student);
//                resultList.add(vo);
//            } else {
//                log.warn("学员ID: {} 未查询到对应学员信息", studentId);
//            }
//        } catch (Exception e) {
//            log.error("查询学员ID: {} 信息出错", studentId, e);
//        }
//    }

    /**
     * 根据班级ID查询所有相关的报名信息和学员信息，支持多字段模糊搜索
     * lqx
     *
     * @param trainingClassId 班级ID
     * @param studentName     姓名（模糊搜索）
     * @param phonenumber     手机号码（模糊搜索）
     * @param idNumber        证件编号（模糊搜索）
     * @return 包含报名信息和学员信息的列表
     */
    @Override
    public List<ClassStudentVO> getClassStudents(
            String trainingClassId,
            String studentName,
            String phonenumber,
            String idNumber) {

        // 1. 查询该班级所有在班学员
        List<ClassStudent> classStudents = classStudentMapper.selectClassStudentsByClassId(trainingClassId);
        if (classStudents == null || classStudents.isEmpty()) {
            log.info("班级ID: {} 没有找到在班学员记录", trainingClassId);
            return new ArrayList<>();
        }

        // 2. 处理学员信息，组装VO列表
        List<ClassStudentVO> resultList = new ArrayList<>();
        for (ClassStudent classStudent : classStudents) {
            ClassStudentVO vo = new ClassStudentVO();

            // 处理报名ID不为空的情况
            if (classStudent.getRegistrationId() != null && !classStudent.getRegistrationId().trim().isEmpty()) {
                try {
                    RegistrationVo queryVo = new RegistrationVo();
                    queryVo.setRegistrationId(classStudent.getRegistrationId());
                    List<RegistrationDto> registrationDtos = registrationService.selectList(queryVo);

                    if (registrationDtos != null && !registrationDtos.isEmpty()) {
                        RegistrationDto registrationDto = registrationDtos.get(0);
                        registrationDto.setPosition(classStudent.getPositionRank());
                        vo.setSourceType("registration");
                        vo.setRegistrationDto(registrationDto);
                        resultList.add(vo);
                    } else {
                        log.warn("报名ID: {} 未查询到对应报名信息", classStudent.getRegistrationId());
                        addStudentInfoToResult(classStudent, resultList);
                    }
                } catch (Exception e) {
                    log.error("查询报名ID: {} 信息出错", classStudent.getRegistrationId(), e);
                    addStudentInfoToResult(classStudent, resultList);
                }
            } else {
                addStudentInfoToResult(classStudent, resultList);
            }
        }

        // 3. 多字段模糊查询过滤（且逻辑）
        if (hasSearchConditions(studentName, phonenumber, idNumber)) {
            resultList = resultList.stream()
                    .filter(vo -> matchesSearchConditions(vo, studentName, phonenumber, idNumber))
                    .collect(Collectors.toList());
        }

        return resultList;
    }

    /**
     * 通过班级id获取学员id
     * lqx
     */
    @Override
    public List<String> selectStudentIdsByClassId(String classId) {
        return classStudentMapper.selectStudentIdsByClassId(classId);
    }

    /**
     * 检查是否有有效的搜索条件
     */
    private boolean hasSearchConditions(String studentName, String phonenumber, String idNumber) {
        return StringUtils.hasText(studentName) ||
                StringUtils.hasText(phonenumber) ||
                StringUtils.hasText(idNumber);
    }

    /**
     * 检查VO是否匹配多字段搜索条件（满足所有传递的条件才匹配）
     * 模糊匹配姓名、手机号码、证件编号（仅对非空参数进行判断）
     */
    private boolean matchesSearchConditions(ClassStudentVO vo, String studentName, String phonenumber, String idNumber) {
        // 处理学员类型数据
        if ("student".equals(vo.getSourceType()) && vo.getStudentsDto() != null) {
            Students student = vo.getStudentsDto();
            boolean match = true; // 默认匹配，再逐个检查非空参数

            // 若传递了studentName，必须满足姓名包含
            if (studentName != null) {
                match = match && student.getStudentName() != null && student.getStudentName().contains(studentName);
            }
            // 若传递了phonenumber，必须满足手机号包含
            if (phonenumber != null) {
                match = match && student.getPhonenumber() != null && student.getPhonenumber().contains(phonenumber);
            }
            // 若传递了idNumber，必须满足证件号包含
            if (idNumber != null) {
                match = match && student.getIdNumber() != null && student.getIdNumber().contains(idNumber);
            }
            return match;
        }
        // 处理报名类型数据
        else if ("registration".equals(vo.getSourceType()) && vo.getRegistrationDto() != null) {
            RegistrationDto registration = vo.getRegistrationDto();
            boolean match = true; // 默认匹配，再逐个检查非空参数

            // 若传递了studentName，必须满足姓名包含
            if (studentName != null) {
                match = match && registration.getStudentName() != null && registration.getStudentName().contains(studentName);
            }
            // 若传递了phonenumber，必须满足手机号包含
            if (phonenumber != null) {
                match = match && registration.getPhonenumber() != null && registration.getPhonenumber().contains(phonenumber);
            }
            // 若传递了idNumber，必须满足证件号包含
            if (idNumber != null) {
                match = match && registration.getIdNumber() != null && registration.getIdNumber().contains(idNumber);
            }
            return match;
        }
        return false;
    }

    /**
     * 添加学员信息到结果列表
     */
    private void addStudentInfoToResult(ClassStudent classStudent, List<ClassStudentVO> resultList) {
        String studentId = classStudent.getStudentId();
        if (studentId == null || studentId.trim().isEmpty()) {
            log.warn("学员ID为空，无法查询学员信息");
            return;
        }

        try {
            Students student = studentsService.selectStudentsByStudentId(studentId);
            if (student != null) {
                ClassStudentVO vo = new ClassStudentVO();
                StudentsDto studentsDto = new StudentsDto();
                BeanUtils.copyProperties(student,studentsDto);
                vo.setSourceType("student");
                studentsDto.setPosition(classStudent.getPositionRank());
                //查询单位名称
                if (!studentsDto.getUnitId().isEmpty()){
                    Units units = unitsMapper.selectUnitsByUnitId(studentsDto.getUnitId());
                    studentsDto.setUnitName(units.getUnitName());
                }
                vo.setStudentsDto(studentsDto);
                resultList.add(vo);
            } else {
                log.warn("学员ID: {} 未查询到对应学员信息", studentId);
            }
        } catch (Exception e) {
            log.error("查询学员ID: {} 信息出错", studentId, e);
        }
    }

    /**
     * 批量进班
     */
    @Override
    @Transactional
    public int batchJoin(List<ClassStudent> classStudentList) {
        Projects projects = projectsMapper.selectProjectsByName("特种设备");
        // 处理每条记录，设置主键和时间等信息
        for (ClassStudent student : classStudentList) {
            // 生成主键ID
            student.setClassStudentId(String.valueOf(snowflake.nextId()));
            // 设置创建时间和更新时间
            student.setCreateTime(DateUtils.getNowDate());
            student.setUpdateTime(DateUtils.getNowDate());
            LoginUser loginUser = SecurityUtils.getLoginUser();
            student.setCreateBy(loginUser.getSysUser().getNickName());
            //设置考试状态-默认未排考
            student.setExamStatus("0");
            //设置满意度调查填写情况(1-已填写，0-未填写)-默认未填写
            student.setSatisfactionSurveyStatus("0");
            // 设置在班状态
            student.setIsRemoved(0L);
            //通过报名id获取项目id
            RegistrationDto registrationDto1 = registrationService.selectRegistrationByRegistrationId(student.getRegistrationId());
            //设置报名id
            student.setProjectId(registrationDto1.getProjectId());
            //修改报名班状态
            if (student.getRegistrationId() != null && !"".equals(student.getRegistrationId())){
                Registration registration = new Registration();
                registration.setRegistrationId(student.getRegistrationId());
                registration.setClassStatus("1");
                //保存班级id
                registration.setExampleThree(student.getTrainingClassId());
                registrationService.updateRegistration(registration);

                RegistrationDto registrationDto = registrationService.selectRegistrationByRegistrationId(student.getRegistrationId());
                if (registrationDto != null){
                    Projects projectsDb = projectsMapper.selectProjectsByProjectId(registrationDto.getProjectId());
                    Projects projectsType = projectsMapper.selectProjectsByProjectId(projectsDb.getpId());
                    if (projects != null && projectsDb.getAncestors().contains(projects.getProjectId())){
                        SpecialCertificate specialCertificate = new SpecialCertificate();
                        specialCertificate.setProjectId(registrationDto.getProjectId());
                        specialCertificate.setStudentId(student.getStudentId());
                        specialCertificate.setCertificateType("1");
                        specialCertificate.setRegistrationId(student.getRegistrationId());
                        specialCertificate.setWorkCategory(projectsType.getProjectName());
                        specialCertificate.setWorkProject(projectsDb.getProjectName());
                        specialCertificate.setCreateBy(loginUser.getSysUser().getUserName());
                        specialCertificate.setCreatedTime(DateUtils.getNowDate());
                        specialCertificate.setTrainingClassId(student.getTrainingClassId());
                        specialCertificate.setSpecialCertificateId(String.valueOf(snowflake.nextId()));
                        specialCertificateMapper.insertSpecialCertificate(specialCertificate);
                    }else {
                        CertificateIssue certificateIssue = new CertificateIssue();
                        certificateIssue.setProjectId(registrationDto.getProjectId());
                        certificateIssue.setStudentId(student.getStudentId());
                        certificateIssue.setCertificateType("1");
                        certificateIssue.setRegistrationId(student.getRegistrationId());
                        certificateIssue.setDigitalStatus("1");
                        certificateIssue.setPaperStatus("1");
                        certificateIssue.setCreatedBy(loginUser.getSysUser().getUserName());
                        certificateIssue.setCreatedTime(DateUtils.getNowDate());
                        certificateIssue.setTrainingClassId(student.getTrainingClassId());
                        certificateIssue.setCertificateIssueId(String.valueOf(snowflake.nextId()));
                        certificateIssueMapper.insertCertificateIssue(certificateIssue);
                    }
                }


            }
        }
        //修改班级状态,设置为已开班
        TrainingClass trainingClass = new TrainingClass();
        trainingClass.setTrainingClassId(classStudentList.get(0).getTrainingClassId());
        trainingClass.setClassStatus("2");
        trainingClassMapper.updateTrainingClass(trainingClass);
        return classStudentMapper.batchInsert(classStudentList);
    }

    /**
     * 批量退班
     */
    @Override
    @Transactional
    public int batchQuit(List<ClassStudent> classStudentList) {
        // 设置更新时间和退班状态
        for (ClassStudent student : classStudentList) {
            if (student.getStudentId() == null || student.getStudentId().isEmpty()) {
                return 100;
            }
            student.setUpdateTime(DateUtils.getNowDate());
            LoginUser loginUser = SecurityUtils.getLoginUser();
            student.setUpdateBy(loginUser.getSysUser().getNickName());
            student.setIsRemoved(2L);
            //修改报名班状态
            if (student.getRegistrationId() != null && !"".equals(student.getRegistrationId())){
                Registration registration = new Registration();
                registration.setRegistrationId(student.getRegistrationId());
                registration.setClassStatus("0");
                registrationService.updateRegistration(registration);

                SpecialCertificate specialCertificate = specialCertificateMapper.selectSpecialCertificateByRegistrationId(student.getRegistrationId());
                if (specialCertificate != null){
                    specialCertificateMapper.deleteSpecialCertificateBySpecialCertificateId(specialCertificate.getSpecialCertificateId());
                }
                CertificateIssue certificateIssue = certificateIssueMapper.selectCertificateIssueByRegistrationId(student.getRegistrationId());
                if (certificateIssue != null){
                    certificateIssueMapper.deleteCertificateIssueByCertificateIssueId(certificateIssue.getCertificateIssueId());
                }
            }
        }
        return classStudentMapper.batchUpdateStatus(classStudentList);
    }

    /**
     * 通过学员id获取学员的考试情况
     * lqx
     */
    @Override
    public List<MyExamInfo> selectExamInfoByStudentId(String studentId) {
        List<MyExamInfo> myExamInfoList = new ArrayList<>();
        //1.获取该学员的班级学员信息
        List<ClassStudent> classStudentList = classStudentMapper.selectClassStudentByStudentId(studentId);
        for (ClassStudent classStudent : classStudentList) {
            MyExamInfo myExamInfo = new MyExamInfo();
            //1.1赋值班级学员信息
            myExamInfo.setClassStudent(classStudent);
            //2.获取考试状态
            myExamInfo.setExamStatus(classStudent.getExamStatus());
            if (!"0".equals(myExamInfo.getExamStatus())){//已排考或者已考试，查询考试安排
                //4.获取考试安排信息
                ExamSchedule examSchedule = examScheduleMapper.selectExamScheduleByExamScheduleId(classStudent.getExamScheduleId());
                if (examSchedule.getExamPathway() != null && !"".equals(examSchedule.getExamPathway())){
                    if ("0".equals(examSchedule.getExamPathway())){
                        examSchedule.setExamPathway("手机");
                    }else if("1".equals(examSchedule.getExamPathway())){
                        examSchedule.setExamPathway("电脑");
                    }else {
                        examSchedule.setExamPathway("手机;电脑");
                    }
                }
                //4.1赋值考试安排信息
                myExamInfo.setExamSchedule(examSchedule);
            }else {//未排考，设置一个空对象
                ExamSchedule examSchedule = new ExamSchedule();
                //4.1赋值考试安排信息
                myExamInfo.setExamSchedule(examSchedule);
            }
            //3.获取班级信息
            TrainClassVo trainClassVo = trainingClassService.selectTrainingClassVoByTrainingClassId(classStudent.getTrainingClassId());
            //3.1赋值班级信息
            myExamInfo.setTrainClassVo(trainClassVo);
            myExamInfoList.add(myExamInfo);
        }
        return myExamInfoList;
    }

    /**
     * 通过学员id获取学员的考试安排
     * lqx
     */
    @Override
    public List<ExamSchedule> selectExamScheduleByStudentId(String studentId,String trainingClassId) {
        List<ExamSchedule> examScheduleList = new ArrayList<>();
        //1.获取该学员的班级学员信息
        List<ClassStudent> classStudentList = classStudentMapper.selectClassStudentByStudentIdAndClassId(studentId,trainingClassId);
        for (ClassStudent classStudent : classStudentList) {
            if (classStudent.getExamScheduleId() != null && !"".equals(classStudent.getExamScheduleId())){
                //获取考试安排信息
                ExamSchedule examSchedule = examScheduleMapper.selectExamScheduleByExamScheduleId(classStudent.getExamScheduleId());
                if (examSchedule != null){
                    //设置考试途径（0-手机、1-电脑）
                    if (examSchedule.getExamPathway() != null && !"".equals(examSchedule.getExamPathway())){
                        if ("0".equals(examSchedule.getExamPathway())){
                            examSchedule.setExamPathway("手机");
                        }else if ("1".equals(examSchedule.getExamPathway())){
                            examSchedule.setExamPathway("电脑");
                        }else {
                            examSchedule.setExamPathway("手机;电脑");
                        }
                    }
                    examScheduleList.add(examSchedule);
                }
            }
        }
        return examScheduleList;
    }
}
